package com.wmyg.antifake.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.wmyg.antifake.annotation.IPCheck;
import com.wmyg.antifake.bean.*;
import com.wmyg.antifake.config.Constant;
import com.wmyg.antifake.message.Message;
import com.wmyg.antifake.service.*;
import com.wmyg.antifake.utils.MaterialCodeUtil;
import cz.mallat.uasparser.OnlineUpdater;
import cz.mallat.uasparser.UASparser;
import cz.mallat.uasparser.UserAgentInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 防伪小程序接口
 *
 */
@Slf4j
@RestController
@RequestMapping("/track")
public class TrackController {

    @Autowired
    FabricService fabricService;

    @Autowired
    BrandService brandService;

    @Autowired
    FactoryService factoryService;

    @Autowired
    ProductService productService;

    @Autowired
    PictureService pictureService;

    /*查询防伪详情*/
    //@IPCheck
    @RequestMapping(value = "/tracker.do")
    public Message track(String itemNo, String address, float longitude, float latitude, String type, String appUserId , HttpServletRequest request){
        log.info("The antifake tracker receive param of itemNo is {}", itemNo);
        LinkedHashMap map = new LinkedHashMap();
        if (type.equals(BarcodeFormat.QR_CODE.name())) {
            return fabricService.track(itemNo, new QueryInfo(new Address(address,new float[]{longitude, latitude},request.getHeader("client-ip")),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),0,request.getHeader("user-agent"),StringUtils.isEmpty(appUserId)?"0":appUserId), request);
        } else if(type.equals(BarcodeFormat.EAN_13.name())){
            List<Picture> pictureList=pictureService.selectPic(4,itemNo,null);
            map.put("barImageUrl", pictureList.size()>0?Constant.PIC_PREFIX+pictureList.get(0).getPicUrl():"");
            map.put("width", pictureList.size()>0?pictureList.get(0).getWidth():"");
            map.put("height", pictureList.size()>0?pictureList.get(0).getHeight():"");
        }else{
            map.put("qrIm", "https://minip.weimengyungu.cn/antifake/track/ean.do?code=" + itemNo);
        }
            map.put("qrString", itemNo);
            map.put("type", type);
        return new Message("0","操作成功",map);
    }

    /**
     * 生成二维码图片
     * @param qR
     * @return
     */
    @RequestMapping(value = "/qr.do", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] createQRImage(String qR) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(MaterialCodeUtil.createQRPic(qR, 1), "jpeg", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    @RequestMapping(value = "/qrcustom.do", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] createQRImageByOption(Integer level, String qR) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(MaterialCodeUtil.createQRPic(qR, level), "jpeg", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
    /*下载二维码接口*/
    @RequestMapping(value = "/image.do")
    public Map image(Integer level, String qR) {
        HashMap<String, String> map = new HashMap<>();
        map.put("qrUrl", "https://minip.weimengyungu.cn/antifake/track/qrcustom.do?level=" + level + "&qR=" + qR);
        return map;
    }

    @RequestMapping(value = "/ean.do", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] createEANImage(String code) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(MaterialCodeUtil.createBarcode(code), "jpeg", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
    /* 详情接口*/
    @RequestMapping(value = "/detail.do")
    public Message getDetails(String id) throws IOException {
        Object context = null;
        String state = "0";
        switch (id.substring(0,1)) {
            case "B" :
                context = getBrandDetail(id.substring(1));
                break;
            case "F" :
                context = getFactoryDetail(id.substring(1));
                break;
            case "P" :
                context = getProductDetail(id.substring(1));
                break;
            default :
                state = "1";
        }
        System.out.println(JSON.toJSON(new Message(state,state .equals("0")?"操作成功":"操作失败" , context)));
        return new Message(state,state .equals("0")?"操作成功":"操作失败" , context);
    }

    private Map getBrandDetail(String id) throws IOException {
        HashMap result = new HashMap();
        result.put("title", brandService.selectById(Integer.parseInt(id)).getBrandName());
        //targetType:对象类型(1 厂家， 2商标，3 商品
        //picType : 1 logo,  2证书  3普通图片
        PictureConvert pictureConvert=pictureService.selectPicConvert(2,id,null);
        ArrayList<ImageInfo> images = getImageInfo(pictureConvert);

        result.put("detail", images);
        return result;
    }

    private Map getFactoryDetail(String id) throws IOException {
        HashMap result = new HashMap();
        result.put("title", factoryService.selectById(Integer.parseInt(id)).getFactoryName());
        //targetType:对象类型(1 厂家， 2商标，3 商品
        //picType : 1 logo,  2证书  3普通图片
        PictureConvert pictureConvert=pictureService.selectPicConvert(1,id,null);
        ArrayList<ImageInfo> images = getImageInfo(pictureConvert);

        result.put("detail", images);
        return result;
    }

    private Map getProductDetail(String id) throws IOException {
        HashMap result = new HashMap();
        result.put("title", productService.selectById(id).getProductName());

        //targetType:对象类型(1 厂家， 2商标，3 商品
        //picType : 1 logo,  2证书  3普通图片
        PictureConvert pictureConvert=pictureService.selectPicConvert(3,id,null);
        ArrayList<ImageInfo> images = getImageInfo(pictureConvert);

        result.put("detail", images);
        return result;
    }

    public ArrayList<ImageInfo> getImageInfo(PictureConvert pictureConvert){
        ArrayList<ImageInfo> images = new ArrayList<>();
        if(pictureConvert.getPic() != null && pictureConvert.getPic().size() != 0){
            List<Picture> list = pictureConvert.getPic();
            for(Picture picture:list){
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.setImageUrl(Constant.PIC_PREFIX+picture.getPicUrl());
                imageInfo.setWidth(picture.getWidth());
                imageInfo.setHeight(picture.getHeight());
                images.add(imageInfo);
            }
        }
        return images;
    }

    /*@RequestMapping(value = "/test.do")
    public String reqHeadTest(HttpServletRequest req) {
        StringBuffer sb = new StringBuffer();
        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String nextElement = headerNames.nextElement();
            sb.append(nextElement+":"+req.getHeader(nextElement) + "<br/><br/>");
        }
        try {
            UASparser uasParser = new UASparser(OnlineUpdater.getVendoredInputStream());
            UserAgentInfo userAgentInfo = uasParser.parse(req.getHeader("user-agent"));
            sb.append("操作系统家族：" + userAgentInfo.getOsFamily() + "<br/><br/>");
            sb.append("操作系统详细名称：" + userAgentInfo.getOsName() + "<br/><br/>");
            sb.append("浏览器名称和版本:" + userAgentInfo.getUaName() + "<br/><br/>");
            sb.append("类型：" + userAgentInfo.getType() + "<br/><br/>");
            sb.append("浏览器名称：" + userAgentInfo.getUaFamily() + "<br/><br/>");
            sb.append("浏览器版本：" + userAgentInfo.getBrowserVersionInfo() + "<br/><br/>");
            sb.append("设备类型：" + userAgentInfo.getDeviceType() + "<br/><br/>");
            sb.append("设备类型：" + userAgentInfo.getDeviceIcon() + "<br/><br/>");
            sb.append("设备类型：" + userAgentInfo.getDeviceInfoUrl() + "<br/><br/>");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }*/

    @RequestMapping(value = "/item/qrcode{itemNo}")
    public Message trackPage(@PathVariable String itemNo){
        return new Message("0",null,itemNo);
    }

    @RequestMapping(value = "/item/r")
    public ModelAndView trackPage(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception  {
        String b = request.getParameter("b");
        String i = request.getParameter("i");
        if(StringUtils.isNotEmpty(b)){
            response.getWriter().print("<script>window.top.location.href='https://minip.weimengyungu.cn/sna/h5/index.html'</script>");
        }else{
            mv.setViewName("show");
            return mv;
        }
        return null;
    }

    @GetMapping("/PmHly9Bpg1.txt")
    public ResponseEntity<FileSystemResource> cert() {
        return export(new File("PmHly9Bpg1.txt"));
    }

    @GetMapping("/")
    public ResponseEntity<FileSystemResource> certs(String filename) {
        return export(new File("PmHly9Bpg1.txt"));
    }

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=PmHly9Bpg1.txt");
        headers.add("Pragma", "no-cache"); headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }
}
